package com.vacomall.spring.jfinal;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;

import com.jfinal.plugin.activerecord.Db;
import com.vacomall.spring.jfinal.annotaion.TxService;
/**
 * Jfinal事务拦截器
 * @author gaojun.zhou
 * @date 2016年8月11日
 *
 */
public class JfinalTransactionInterceptor implements MethodInterceptor {
	
	private final Logger logger = Logger.getLogger(JfinalTransactionInterceptor.class);
	
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Object target = invocation.getThis();
		Method targetMethod = invocation.getMethod();
		Class<?>[] targetMethodParamTypes = targetMethod.getParameterTypes();
		
		Method method = target.getClass().getMethod(targetMethod.getName(),targetMethodParamTypes);
		if (method.isAnnotationPresent(TxService.class)) { 
			
			logger.debug("Transaction statrt intercept method :"+target.getClass().getName()+"."+targetMethod.getName());
			
			AtomImpl invoke = new AtomImpl(invocation);
			boolean atom = Db.tx(invoke);
			
			if(!atom){
				logger.error("Transaction rollback, exception "+invoke.getE().getMessage());
				throw invoke.getE();
			}
			logger.info("Transaction commit success.");
			return invoke.getResult();
		}
		return invocation.proceed(); 
	}
}